import { ref } from "vue";
import { defineStore } from "pinia";
import {
  getAdcodeForCityName,
  getCityWeatherForAdcode,
  getCityNameForIp,
} from "../api/user";
import { useRouter } from "vue-router";
import { onBeforeMount } from "vue";

export const useWeatherStore = defineStore("weather", () => {
  const adcode = ref("");
  const cityName = ref("");
  const cityWeather = ref("");
  const citycode = ref("");
  const currentIpCityName = ref("");
  const state = ref(true);
  const isDisabled = ref(true);
  const cityList = ref([]);
  const cityAddressList = ref([]);
  const localCityAddressList = ref([]);
  const WeatherInfos = ref([]);
  const WeatherInfoCurrent = ref([]);
  const WeatherInfoList = ref([]);
  const localCityList = ref([]);
  const localCityInfo = ref([]);
  const localWeatherInfoCurrent = ref([]);
  const weekList = ref([
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
    "星期日",
  ]);
  const router = useRouter();

  const getAdcode = async (
    cityTemp,
    shouldAssignAdcode = true,
    shouldAssignCityTemp = false,
    shouldAssignLocalStrong = false
  ) => {
    try {
      // 不管怎么着都得触发一次
      const res = await getAdcodeForCityName(cityTemp);
      if (res && res.geocodes && res.geocodes.length > 0) {
        // 防止对adcode重新进行赋值
        if (shouldAssignAdcode == true) {
          adcode.value = res.geocodes[0].adcode;
          citycode.value = res.geocodes[0].citycode;
        }
        // 维护2套信息，当adcode不进行重新赋值，直接进入这，默认不执行
        
        if (shouldAssignCityTemp==true) {
          console.log(res, "看res结构");
          currentIpCityName.value = res.geocodes[0].city;
          console.log(res.geocodes[0].adcode,"ip天气信息AAAA");
          await getWeatherInfo(res.geocodes[0].adcode, true);
        } 
        // 第三套，从localstorage中直接读取adcode，也不用进行重新赋值，存到另一个变量中
        else if(shouldAssignLocalStrong==true){
          await getWeatherInfo(adcode.value);
        }
        else {
          await getWeatherInfo(adcode.value);
        }
      }
    } catch (error) {
      console.error("Failed to get adcode:", error);
    }
  };

  const getWeatherInfo = async (adcodeTemp, isfalse = false) => {
    // 查询预报天气信息
    try {
      const res = await getCityWeatherForAdcode(adcodeTemp, "all");
      WeatherInfoList.value = [];
      if (res) {
        WeatherInfos.value = res.forecasts[0].casts[0];

        for (let i = 0; i < res.forecasts[0].casts.length; i++) {
          WeatherInfoList.value.push(res.forecasts[0].casts[i]);
        }
        console.log(WeatherInfoList.value[0], "查询预报天气信息");
        state.value = true;
      }
    } catch (error) {
      console.error("Failed to get weather info:", error);
    }
    // // 查询实况天气信息，对实况天气进行分类
    // ip地址天气信息存到一个变量中
    if (isfalse == true) {
      const currentIpInfo = await getCityWeatherForAdcode(adcodeTemp, "base");
      localWeatherInfoCurrent.value = [];
      if (currentIpInfo) {
        localWeatherInfoCurrent.value = currentIpInfo.lives[0];
        console.log(localWeatherInfoCurrent, "查询ip实况天气信息");
      }
   
    }
    
    else{
      // // 其他地址天气信息存到另一个变量中
    // 查询实况天气信息
    const currentInfo = await getCityWeatherForAdcode(adcodeTemp, "base");
    WeatherInfoCurrent.value = [];
    if (currentInfo) {
      WeatherInfoCurrent.value = currentInfo.lives[0];
      console.log(WeatherInfoCurrent, "查询实况天气信息");
    }
    }
    
  };

  // 通过ip地址获取城市天气信息
  // 通过ip查询走local那一套
  const getCityname = async (ipTemp) => {
    localCityList.value = await getCityNameForIp(ipTemp);
    console.log(localCityList.value, "ip天气信息localCityList");
    await getAdcode(localCityList.value.city, false, true);
  };

  const plusHandler = () => {
    isDisabled.value = false;
    console.log(cityName, "点击触发");
    if (cityName !== null) {
      cityList.value.push({
        cityAdcode: adcode.value,
        cityName: WeatherInfoCurrent.value.city,
        cityWeather: `${WeatherInfoCurrent.value.temperature}度`,
      });
      console.log(cityList, "cityList的元素");
      // 更新 localStorage
      localStorage.setItem("cityList", JSON.stringify(cityList.value));
      console.log(localStorage,'localStorage中的元素')
      cityName.value = "";
    }
  };

  const lookHandler = async (index) => {
    console.log(index, "点击触发一次");
    isDisabled.value = false;
    adcode.value = cityList.value[index].cityAdcode;
    await getAdcode(cityList.value[index].cityName, false,false,true); // 等待获取 adcode 的值
    router
      .push({
        name: "weatherInfo",
        params: { city: cityList.value[index].cityAdcode },
        query: { search: cityList.value[index].cityName },
      })
      .then(() => {
        console.log("路由跳转到weatherInfo！");
        state.value = false;
      })
      .catch((error) => {
        console.error("路由跳转到weatherInfo失败：", error);
      });
  };

  const deleteHandler = (index) => {
    deleteCity(cityList.value[index].cityAdcode);
    console.log(cityList.value, "cityList");
  };

  // 删除 cityList 中的特定城市
  const deleteCity = (cityAdcode) => {
    cityList.value = cityList.value.filter(
      (city) => city.cityAdcode !== cityAdcode
    );
    console.log(cityList.value, "cityList删除后的");
    // 更新 localStorage
    localStorage.setItem("cityList", JSON.stringify(cityList.value));
  };

  // 读取 localStorage 中的 cityList
  onBeforeMount(() => {
    const storedCityList = localStorage.getItem("cityList");
    if (storedCityList) {
      cityList.value = JSON.parse(storedCityList);
    }
    
  });

  return {
    adcode,
    cityName,
    cityWeather,
    state,
    cityList,
    currentIpCityName,
    WeatherInfos,
    WeatherInfoList,
    WeatherInfoCurrent,
    isDisabled,
    weekList,
    citycode,
    localCityList,
    localCityInfo,
    localCityAddressList,
    localWeatherInfoCurrent,
    getAdcode,
    getWeatherInfo,
    plusHandler,
    lookHandler,
    deleteHandler,
    deleteCity,
    getCityname,
  };
});
